<?php
function randomString($length = 32)
{
    // 定义字符集
    $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';

    // 生成随机字符串
    for ($i = 0; $i < $length; $i++) {
        // 从字符集中随机选取一个字符
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }

    return $randomString;
}

function success($message = "SUCCESS", $code = 200)
{
    $data = ["code" => $code, "message" => $message];

    return json($data);
}

function fail($message = "FAIL", $code = 400)
{
    $data = ["code" => $code, "message" => $message];

    return json($data);
}

function data($data, $message = "SUCCESS", $code = 200)
{
    $result =  ["code" => $code, "message" => $message, "result" => $data];

    return json($result);
}

function dataByPage($paginate)
{
    return data([
        'list' => $paginate->items(),
        'total' => $paginate->total(),
        'page' => $paginate->currentPage(),
        'pageSize' => $paginate->perPage(),
        'lastPage' => $paginate->lastPage(),
        'hasMorePages' => $paginate->hasMorePages()
    ]);
}

/**
 * 构建树形结构数据
 */
function buildTreeData($menus, $parentId = null): array
{
    $tree = [];

    foreach ($menus as $menu) {
        if ($menu->parent_id == $parentId) {
            $children = buildTreeData($menus, $menu->id);
            if (!empty($children)) {
                $menu->children = $children;
            }
            $tree[] = $menu;
        }
    }

    return $tree;
}